<template>
  <div class="homework-create-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="page-title-section">
          <span class="title-icon">📚</span>
          <h1 class="page-title">新增作业</h1>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <div class="container">
        <!-- 作业基本信息 -->
        <div class="form-section">
          <div class="form-row">
            <div class="form-group">
              <label>标题</label>
              <input 
                v-model="homeworkForm.title" 
                type="text" 
                placeholder="请输入标题"
                class="form-input large"
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>开始时间</label>
              <input 
                v-model="homeworkForm.startTime" 
                type="text" 
                placeholder="示例：2025-10-08 10:00:00"
                class="form-input"
              />
            </div>
            
            <div class="form-group">
              <label>结束时间</label>
              <input 
                v-model="homeworkForm.endTime" 
                type="text" 
                placeholder="示例：2025-10-08 10:00:00"
                class="form-input"
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group full-width">
              <label>描述</label>
              <textarea 
                v-model="homeworkForm.description" 
                class="form-textarea"
                rows="8"
                placeholder="请输入作业描述..."
              ></textarea>
            </div>
          </div>
        </div>

        <!-- 题目选择区域 -->
        <div class="questions-section">
          <div class="section-tabs">
            <button 
              :class="['tab-btn', { active: activeTab === 'homework' }]"
              @click="activeTab = 'homework'"
            >
              我的试题
            </button>
            <button 
              :class="['tab-btn', { active: activeTab === 'public' }]"
              @click="activeTab = 'public'"
            >
              公开题库
            </button>
          </div>

          <!-- 我的试题列表 -->
          <div v-if="activeTab === 'homework'" class="questions-list">
            <!-- 搜索栏 -->
            <div class="search-filter-bar">
              <input 
                type="text" 
                v-model="mySearchKeyword" 
                placeholder="搜索题目标题..."
                class="search-input"
                @keyup.enter="searchMyQuestions"
              >
              <select v-model="mySearchDifficulty" class="difficulty-select">
                <option value="">全部难度</option>
                <option value="1">难度 1</option>
                <option value="2">难度 2</option>
                <option value="3">难度 3</option>
                <option value="4">难度 4</option>
                <option value="5">难度 5</option>
                <option value="6">难度 6</option>
              </select>
              <button @click="searchMyQuestions" class="search-btn">
                <i class="fas fa-search"></i>
                搜索
              </button>
              <button @click="resetMySearch" class="reset-btn">
                <i class="fas fa-redo"></i>
                重置
              </button>
            </div>
            
            <div class="questions-table-container">
              <table class="questions-table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>标题</th>
                    <th>类型</th>
                    <th>权重</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-if="availableQuestions.length === 0">
                    <td colspan="5" class="empty-row">暂无我的试题</td>
                  </tr>
                  <tr v-for="question in availableQuestions" :key="question.id" class="table-row">
                    <td>{{ question.id }}</td>
                    <td class="title-cell">{{ question.title }}</td>
                    <td>{{ question.type }}</td>
                    <td>{{ question.weight }}</td>
                    <td class="action-cell">
                      <button @click="addQuestionToHomework(question)" class="add-btn">+</button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- 分页控件 -->
            <div class="pagination" v-if="myQuestionsPagination.total > 0">
              <button 
                @click="changeMyQuestionsPage(myQuestionsPagination.current - 1)" 
                :disabled="myQuestionsPagination.current === 1"
                class="page-btn"
              >
                上一页
              </button>
              <span class="page-info">
                第 {{ myQuestionsPagination.current }} / {{ myQuestionsPagination.pages }} 页
                (共 {{ myQuestionsPagination.total }} 条)
              </span>
              <div class="page-jump">
                <input 
                  v-model.number="myJumpPage" 
                  type="number" 
                  min="1" 
                  :max="myQuestionsPagination.pages"
                  placeholder="页码"
                  class="page-input"
                  @keyup.enter="jumpToMyQuestionsPage"
                />
                <button @click="jumpToMyQuestionsPage" class="jump-btn">跳转</button>
              </div>
              <button 
                @click="changeMyQuestionsPage(myQuestionsPagination.current + 1)" 
                :disabled="myQuestionsPagination.current === myQuestionsPagination.pages"
                class="page-btn"
              >
                下一页
              </button>
            </div>
          </div>

          <!-- 公开题库列表 -->
          <div v-if="activeTab === 'public'" class="questions-list">
            <!-- 搜索栏 -->
            <div class="search-filter-bar">
              <input 
                type="text" 
                v-model="publicSearchKeyword" 
                placeholder="搜索题目标题..."
                class="search-input"
                @keyup.enter="searchPublicQuestions"
              >
              <select v-model="publicSearchDifficulty" class="difficulty-select">
                <option value="">全部难度</option>
                <option value="1">难度 1</option>
                <option value="2">难度 2</option>
                <option value="3">难度 3</option>
                <option value="4">难度 4</option>
                <option value="5">难度 5</option>
                <option value="6">难度 6</option>
              </select>
              <button @click="searchPublicQuestions" class="search-btn">
                <i class="fas fa-search"></i>
                搜索
              </button>
              <button @click="resetPublicSearch" class="reset-btn">
                <i class="fas fa-redo"></i>
                重置
              </button>
            </div>
            
            <div class="questions-table-container">
              <table class="questions-table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>标题</th>
                    <th>类型</th>
                    <th>权重</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-if="availableQuestions.length === 0">
                    <td colspan="5" class="empty-row">暂无公开题目</td>
                  </tr>
                  <tr v-for="question in availableQuestions" :key="question.id" class="table-row">
                    <td>{{ question.id }}</td>
                    <td class="title-cell">{{ question.title }}</td>
                    <td>{{ question.type }}</td>
                    <td>{{ question.weight }}</td>
                    <td class="action-cell">
                      <button @click="addQuestionToHomework(question)" class="add-btn">+</button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- 分页控件 -->
            <div class="pagination" v-if="publicQuestionsPagination.total > 0">
              <button 
                @click="changePublicQuestionsPage(publicQuestionsPagination.current - 1)" 
                :disabled="publicQuestionsPagination.current === 1"
                class="page-btn"
              >
                上一页
              </button>
              <span class="page-info">
                第 {{ publicQuestionsPagination.current }} / {{ publicQuestionsPagination.pages }} 页
                (共 {{ publicQuestionsPagination.total }} 条)
              </span>
              <div class="page-jump">
                <input 
                  v-model.number="publicJumpPage" 
                  type="number" 
                  min="1" 
                  :max="publicQuestionsPagination.pages"
                  placeholder="页码"
                  class="page-input"
                  @keyup.enter="jumpToPublicQuestionsPage"
                />
                <button @click="jumpToPublicQuestionsPage" class="jump-btn">跳转</button>
              </div>
              <button 
                @click="changePublicQuestionsPage(publicQuestionsPagination.current + 1)" 
                :disabled="publicQuestionsPagination.current === publicQuestionsPagination.pages"
                class="page-btn"
              >
                下一页
              </button>
            </div>
          </div>
        </div>

        <!-- 本次作业题目 -->
        <div class="homework-questions-section">
          <div class="section-header">
            <span class="section-number">2</span>
            <span class="section-title">📝 本次作业题</span>
            <span class="questions-count">{{ selectedQuestions.length }} 道试题</span>
          </div>

          <div class="homework-questions-table">
            <table class="questions-table">
              <thead>
                <tr>
                  <th>序号</th>
                  <th>标题</th>
                  <th>类型</th>
                  <th>权重</th>
                  <th>分数</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="selectedQuestions.length === 0">
                  <td colspan="6" class="empty-row">
                    暂无选择作业题目
                    <br />
                    <span class="tip">请从 <span class="highlight">我的试题题库</span> 选择题目</span>
                  </td>
                </tr>
                <tr v-for="(question, index) in selectedQuestions" :key="question.id" class="table-row">
                  <td>{{ index + 1 }}</td>
                  <td class="title-cell">{{ question.title }}</td>
                  <td>{{ question.type }}</td>
                  <td>{{ question.weight }}</td>
                  <td class="score-cell">
                    <input 
                      v-model.number="question.score" 
                      type="number" 
                      min="0"
                      step="1"
                      placeholder="分数"
                      class="score-input"
                    />
                  </td>
                  <td class="action-cell">
                    <button @click="removeQuestionFromHomework(index)" class="remove-btn">移除</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- 选择团队 -->
        <div class="team-section">
          <div class="section-header">
            <h3 class="section-title">选择班级</h3>
            <button @click="loadMyTeams" class="refresh-teams-btn" :disabled="isLoadingTeams" title="刷新班级列表">
              <i class="icon">🔄</i>
              {{ isLoadingTeams ? '加载中...' : '刷新' }}
            </button>
          </div>
          
          <!-- 加载中提示 -->
          <div v-if="isLoadingTeams && teams.length === 0" class="loading-teams">
            <div class="loading-spinner"></div>
            <p>正在加载班级信息...</p>
          </div>
          
          <!-- 班级列表 -->
          <div v-else-if="teams.length > 0" class="team-grid">
            <div 
              v-for="team in teams" 
              :key="team.id"
              :class="['team-card', { selected: selectedTeams.includes(team.id) }]"
              @click="toggleTeam(team.id)"
            >
              <div class="team-icon">🏫</div>
              <div class="team-name">{{ team.name }}</div>
              <div class="team-id">ID: {{ team.id }}</div>
              <div v-if="team.memberCount" class="team-member-count">
                <i class="icon">👥</i>
                {{ team.memberCount }} 人
              </div>
            </div>
          </div>
          
          <!-- 无班级提示 -->
          <div v-else class="no-teams">
            <i class="icon">📭</i>
            <p>暂无班级信息</p>
            <small>请先创建或加入班级</small>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button @click="createNewHomework" class="create-btn">新建</button>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import api from '@/api/config'
import API_CONFIG from '@/api/apiConfig'
import { getCurrentUserId } from '@/utils/userIdUtils'
import { getMyCreatQuestion } from '@/api/homework'
import { getTestQuestionList } from '@/api/testQuestion'
import { teamApi } from '@/api/team'
import logger from '../utils/logger.js'

export default {
  name: 'HomeworkCreate',
  setup() {
    // 响应式数据
    const activeTab = ref('homework')
    const availableQuestions = ref([])
    const selectedQuestions = ref([])
    const selectedTeams = ref([])
    const myJumpPage = ref(null) // 我的试题跳转页码
    const publicJumpPage = ref(null) // 公开题库跳转页码
    
    // 搜索条件 - 我的试题
    const mySearchKeyword = ref('')
    const mySearchDifficulty = ref('')
    
    // 搜索条件 - 公开题库
    const publicSearchKeyword = ref('')
    const publicSearchDifficulty = ref('')

    // 分页数据 - 我的试题
    const myQuestionsPagination = reactive({
      current: 1,
      size: 10,
      total: 0,
      pages: 0
    })

    // 分页数据 - 公开题库
    const publicQuestionsPagination = reactive({
      current: 1,
      size: 10,
      total: 0,
      pages: 0
    })

    // 表单数据
    const homeworkForm = reactive({
      title: '',
      startTime: '',
      endTime: '',
      description: ''
    })

    // 团队数据
    const teams = ref([])
    const isLoadingTeams = ref(false)

    // 模拟可用题目数据（已弃用，保留作为参考）
    const mockQuestions = [
      {
        id: '44930',
        title: '信号拒绝',
        type: 'toc',
        weight: '简单题'
      },
      {
        id: '44926',
        title: '挂灯笼',
        type: 'toc',
        weight: '简单题'
      },
      {
        id: '44924',
        title: '小明',
        type: 'toc',
        weight: '简单题'
      },
      {
        id: '44921',
        title: '红苹果',
        type: 'toc',
        weight: '简单题'
      },
      {
        id: '32979',
        title: '勾股定理',
        type: 'toc',
        weight: '简单题'
      },
      {
        id: '32978',
        title: '删除',
        type: 'toc',
        weight: '简单题'
      },
      {
        id: '32977',
        title: '枝状数据库',
        type: 'toc',
        weight: '简单题'
      },
      {
        id: '32972',
        title: '冰淇淋味',
        type: 'toc',
        weight: '简单题'
      },
      {
        id: '32971',
        title: '图形堆',
        type: 'toc',
        weight: '简单题'
      },
      {
        id: '32968',
        title: '写数字',
        type: 'toc',
        weight: '简单题'
      }
    ]

    // 方法
    const loadQuestions = () => {
      // 这里应该调用API获取用户的题目库
      availableQuestions.value = mockQuestions
    }

    // 加载我的试题
    const loadMyQuestions = async (page = 1) => {
      try {
        logger.log('📚 [HomeworkCreate] 开始获取我的试题，第', page, '页')
        
        // 构建查询参数
        const params = {
          page: page,
          size: myQuestionsPagination.size
        }
        
        // 添加搜索条件
        if (mySearchKeyword.value) {
          params.keyword = mySearchKeyword.value
          logger.log('🔍 [HomeworkCreate] 搜索关键词:', mySearchKeyword.value)
        }
        if (mySearchDifficulty.value) {
          params.difficulty = parseInt(mySearchDifficulty.value)
          logger.log('🔍 [HomeworkCreate] 搜索难度:', mySearchDifficulty.value)
        }
        
        const response = await getMyCreatQuestion(params)
        
        logger.log('✅ [HomeworkCreate] 我的试题获取成功:', response)
        logger.log('📦 [HomeworkCreate] 完整响应数据:', response.data)
        
        // 难度映射：将数字转换为文字
        const difficultyMap = {
          1: '简单题',
          2: '中等题',
          3: '困难题'
        }
        
        // 处理响应数据 - 数据在 response.data.records 数组中
        if (response && response.data && response.data.records) {
          logger.log('📊 [HomeworkCreate] records数量:', response.data.records.length)
          
          // 更新分页信息
          myQuestionsPagination.current = response.data.current || page
          myQuestionsPagination.total = response.data.total || 0
          myQuestionsPagination.pages = response.data.pages || 0
          
          // 转换数据格式以匹配现有的题目格式
          availableQuestions.value = response.data.records.map(question => {
            const mappedQuestion = {
              id: question.id,
              title: question.questionName,
              type: 'toc',  // 修改为toc
              weight: difficultyMap[question.difficulty] || '简单题'
            }
            logger.log('🔄 [HomeworkCreate] 映射题目:', mappedQuestion)
            return mappedQuestion
          })
          
          logger.log('✅ [HomeworkCreate] 题目列表更新完成，总数:', availableQuestions.value.length)
          logger.log('📊 [HomeworkCreate] 分页信息:', myQuestionsPagination)
        } else {
          logger.warn('⚠️ [HomeworkCreate] 响应数据格式异常，response.data:', response?.data)
          availableQuestions.value = []
        }
      } catch (error) {
        logger.error('❌ [HomeworkCreate] 获取我的试题失败:', error)
        // 如果API调用失败，显示空列表
        availableQuestions.value = []
      }
    }

    // 搜索我的试题
    const searchMyQuestions = () => {
      logger.log('🔍 [HomeworkCreate] 搜索我的试题')
      myQuestionsPagination.current = 1  // 重置到第一页
      loadMyQuestions(1)
    }
    
    // 重置我的试题搜索
    const resetMySearch = () => {
      logger.log('🔄 [HomeworkCreate] 重置我的试题搜索条件')
      mySearchKeyword.value = ''
      mySearchDifficulty.value = ''
      myQuestionsPagination.current = 1
      loadMyQuestions(1)
    }
    
    // 搜索公开题库
    const searchPublicQuestions = () => {
      logger.log('🔍 [HomeworkCreate] 搜索公开题库')
      publicQuestionsPagination.current = 1  // 重置到第一页
      loadPublicQuestions(1)
    }
    
    // 重置公开题库搜索
    const resetPublicSearch = () => {
      logger.log('🔄 [HomeworkCreate] 重置公开题库搜索条件')
      publicSearchKeyword.value = ''
      publicSearchDifficulty.value = ''
      publicQuestionsPagination.current = 1
      loadPublicQuestions(1)
    }
    
    // 切换我的试题页码
    const changeMyQuestionsPage = (page) => {
      if (page < 1 || page > myQuestionsPagination.pages) return
      loadMyQuestions(page)
    }

    // 加载公开题库
    const loadPublicQuestions = async (page = 1) => {
      try {
        logger.log('📚 [HomeworkCreate] 开始获取公开题库，第', page, '页')
        
        // 构建查询参数
        const params = {
          isPublic: 1,
          page: page,
          size: publicQuestionsPagination.size
        }
        
        // 添加搜索条件
        if (publicSearchKeyword.value) {
          params.keyword = publicSearchKeyword.value
          logger.log('🔍 [HomeworkCreate] 搜索关键词:', publicSearchKeyword.value)
        }
        if (publicSearchDifficulty.value) {
          params.difficulty = parseInt(publicSearchDifficulty.value)
          logger.log('🔍 [HomeworkCreate] 搜索难度:', publicSearchDifficulty.value)
        }
        
        const response = await getTestQuestionList(params)
        
        logger.log('✅ [HomeworkCreate] 公开题库获取成功:', response)
        logger.log('📦 [HomeworkCreate] 完整响应数据:', response.data)
        
        // 难度映射：将数字转换为文字
        const difficultyMap = {
          1: '简单题',
          2: '中等题',
          3: '困难题'
        }
        
        // 处理响应数据 - 数据在 response.data.records 数组中
        if (response && response.data && response.data.records) {
          logger.log('📊 [HomeworkCreate] 公开题库数量:', response.data.records.length)
          
          // 更新分页信息
          publicQuestionsPagination.current = response.data.current || page
          publicQuestionsPagination.total = response.data.total || 0
          publicQuestionsPagination.pages = response.data.pages || Math.ceil(response.data.total / publicQuestionsPagination.size)
          
          logger.log('📄 [HomeworkCreate] 分页详情:')
          logger.log('  - 当前页:', publicQuestionsPagination.current)
          logger.log('  - 总记录数:', publicQuestionsPagination.total)
          logger.log('  - 总页数:', publicQuestionsPagination.pages)
          
          // 转换数据格式以匹配现有的题目格式
          availableQuestions.value = response.data.records.map(question => {
            const mappedQuestion = {
              id: question.id,
              title: question.questionName,
              type: 'toc',  // 修改为toc
              weight: difficultyMap[question.difficulty] || '简单题'
            }
            return mappedQuestion
          })
          
          logger.log('✅ [HomeworkCreate] 公开题库列表更新完成，总数:', availableQuestions.value.length)
          logger.log('📊 [HomeworkCreate] 分页信息:', publicQuestionsPagination)
        } else {
          logger.warn('⚠️ [HomeworkCreate] 响应数据格式异常，response.data:', response?.data)
          availableQuestions.value = []
        }
      } catch (error) {
        logger.error('❌ [HomeworkCreate] 获取公开题库失败:', error)
        // 如果API调用失败，显示空列表
        availableQuestions.value = []
      }
    }

    // 切换公开题库页码
    const changePublicQuestionsPage = (page) => {
      if (page < 1 || page > publicQuestionsPagination.pages) return
      loadPublicQuestions(page)
    }

    // 跳转到我的试题指定页码
    const jumpToMyQuestionsPage = () => {
      if (!myJumpPage.value) {
        alert('请输入页码')
        return
      }
      
      if (myJumpPage.value < 1 || myJumpPage.value > myQuestionsPagination.pages) {
        alert(`请输入有效的页码（1-${myQuestionsPagination.pages}）`)
        return
      }
      
      logger.log('🎯 [HomeworkCreate] 跳转到我的试题第', myJumpPage.value, '页')
      loadMyQuestions(myJumpPage.value)
      myJumpPage.value = null // 清空输入框
    }

    // 跳转到公开题库指定页码
    const jumpToPublicQuestionsPage = () => {
      if (!publicJumpPage.value) {
        alert('请输入页码')
        return
      }
      
      if (publicJumpPage.value < 1 || publicJumpPage.value > publicQuestionsPagination.pages) {
        alert(`请输入有效的页码（1-${publicQuestionsPagination.pages}）`)
        return
      }
      
      logger.log('🎯 [HomeworkCreate] 跳转到公开题库第', publicJumpPage.value, '页')
      loadPublicQuestions(publicJumpPage.value)
      publicJumpPage.value = null // 清空输入框
    }

    const addQuestionToHomework = (question) => {
      // 检查是否已经添加过
      const exists = selectedQuestions.value.find(q => q.id === question.id)
      if (!exists) {
        selectedQuestions.value.push({ ...question, score: 0 })
        logger.log('添加题目到作业:', question)
      } else {
        alert('该题目已经添加过了')
      }
    }

    const removeQuestionFromHomework = (index) => {
      selectedQuestions.value.splice(index, 1)
    }

    // 获取用户ID - 从JWT令牌中解析
    const getUserId = () => {
      try {
        const token = localStorage.getItem('token')
        if (token) {
          // JWT令牌由三部分组成，用.分隔：header.payload.signature
          const parts = token.split('.')
          if (parts.length === 3) {
            // 解码payload部分（base64url编码）
            const payload = parts[1]
            // 添加必要的padding
            const paddedPayload = payload + '='.repeat((4 - payload.length % 4) % 4)
            // base64url解码
            const decodedPayload = atob(paddedPayload.replace(/-/g, '+').replace(/_/g, '/'))
            
            // 使用正则表达式处理大整数ID
            const fixedJsonString = decodedPayload.replace(
              /"(id|userId|teamId|questionId|homeworkId|newsId)":\s*(\d{15,})/g,
              '"$1":"$2"'
            )
            
            const payloadObj = JSON.parse(fixedJsonString)
            
            // 从claims中获取id
            if (payloadObj.claims && payloadObj.claims.id) {
              const userId = payloadObj.claims.id
              logger.log('👤 [HomeworkCreate] 从JWT令牌获取用户ID:', userId, '类型:', typeof userId)
              return userId
            }
          }
        }
        
        // 回退方案
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        return userInfo.userId || userInfo.id || ''
      } catch (error) {
        logger.error('❌ [HomeworkCreate] 解析JWT令牌失败:', error)
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        return userInfo.userId || userInfo.id || ''
      }
    }
    
    // 加载我的班级
    const loadMyTeams = async () => {
      isLoadingTeams.value = true
      
      try {
        const userId = getUserId()
        if (!userId) {
          alert('用户信息获取失败，请重新登录')
          return
        }
        
        logger.log('🏫 [HomeworkCreate] 开始加载我的班级')
        logger.log('👤 [HomeworkCreate] 用户ID:', userId)
        
        // 调用获取班级信息的API
        const response = await teamApi.findById(userId)
        
        logger.log('✅ [HomeworkCreate] 班级信息获取成功:', response)
        
        // 处理响应数据
        if (response && response.code === 0) {
          const teamData = response.data
          
          if (teamData) {
            // 如果返回单个班级对象
            if (teamData.id) {
              teams.value = [{
                id: teamData.id,
                number: teamData.id,
                name: teamData.teamName || teamData.name || '未命名班级',
                description: teamData.description,
                memberCount: teamData.memberCount || 0
              }]
            }
            // 如果返回班级数组
            else if (Array.isArray(teamData)) {
              teams.value = teamData.map(team => ({
                id: team.id,
                number: team.id,
                name: team.teamName || team.name || '未命名班级',
                description: team.description,
                memberCount: team.memberCount || 0
              }))
            }
            
            logger.log('🏫 [HomeworkCreate] 班级列表:', teams.value)
            logger.log(`✅ [HomeworkCreate] 成功加载 ${teams.value.length} 个班级`)
            
            // 静默加载，不显示成功提示（只在用户主动刷新时提示）
            if (teams.value.length === 0) {
              logger.warn('⚠️ [HomeworkCreate] 暂无班级信息')
            }
          } else {
            teams.value = []
            if (window.$message?.info) {
              window.$message.info('暂无班级信息')
            } else {
              alert('暂无班级信息')
            }
          }
        } else {
          const errorMsg = response?.message || '获取班级信息失败'
          logger.error('❌ [HomeworkCreate] 业务错误:', errorMsg)
          if (window.$message?.error) {
            window.$message.error(errorMsg)
          } else {
            alert(errorMsg)
          }
        }
      } catch (error) {
        logger.error('❌ [HomeworkCreate] 加载班级失败:', error)
        
        const errorMessage = error.response?.data?.message || error.message || '加载班级失败，请重试'
        if (window.$message?.error) {
          window.$message.error(errorMessage)
        } else {
          alert(errorMessage)
        }
      } finally {
        isLoadingTeams.value = false
      }
    }
    
    const toggleTeam = (teamId) => {
      const index = selectedTeams.value.indexOf(teamId)
      if (index > -1) {
        selectedTeams.value.splice(index, 1)
      } else {
        selectedTeams.value.push(teamId)
      }
    }



    const createNewHomework = async () => {
      if (selectedQuestions.value.length === 0) {
        alert('请至少选择一道题目')
        return
      }
      if (selectedTeams.value.length === 0) {
        alert('请至少选择一个团队')
        return
      }
      
      try {
        logger.log('📝 [HomeworkCreate] 开始创建作业')
        
        // 构建API请求数据 (根据接口文档格式)
        const homeworkData = {
          title: homeworkForm.title || '数学作业',
          description: homeworkForm.description || '请完成以下数学题目',
          teacherId: getCurrentUserId(), // 添加正确的教师ID
          // 改为支持多班级：后端参数 teamIds 为 List<Long>
          teamIds: Array.isArray(selectedTeams.value) ? selectedTeams.value.slice() : [],
          startTime: homeworkForm.startTime || '2023-10-15 08:00:00',
          endTime: homeworkForm.endTime || '2023-10-20 23:59:59',
          totalScore: 100,
          questions: selectedQuestions.value.map((question, index) => ({
            testQuestionId: parseInt(question.id),
            sortOrder: index + 1,
            score: question.score || 0  // 使用用户设置的分数，默认为0
          }))
        }
        
        logger.log('🌐 [HomeworkCreate] 调用接口:', API_CONFIG.getFullURL(API_CONFIG.ENDPOINTS.HOMEWORK_CREATE))
        logger.log('📊 [HomeworkCreate] 请求数据:', homeworkData)
        
        // 调用创建作业API（不需要/api前缀）
        const response = await api.post(API_CONFIG.ENDPOINTS.HOMEWORK_CREATE, homeworkData)
        
        logger.log('✅ [HomeworkCreate] 作业API调用完成:', response)
        logger.log('🔍 [HomeworkCreate] 响应数据调试:')
        logger.log('  - response:', response)
        logger.log('  - response.code:', response?.code)
        logger.log('  - response.message:', response?.message)
        
        // 🔥 只有当 code === 0 时才是真正成功
        if (response && response.code === 0) {
          logger.log('✅ [HomeworkCreate] 作业创建成功（code = 0）');
          
          // 移除成功提示，直接跳转以改善用户体验
          // const successMsg = response.message || '作业创建成功！';
          // alert(successMsg)
          
          // 同时保存到localStorage作为备份
          const newHomework = {
            id: (typeof response === 'object' ? response.data?.id : null) || Date.now(),
            title: homeworkData.title,
            startTime: homeworkData.startTime,
            endTime: homeworkData.endTime,
            questionCount: selectedQuestions.value.length,
            registrationCount: 0,
            status: '未发布',
            creator: '当前用户',
            questions: selectedQuestions.value,
            teams: selectedTeams.value,
            description: homeworkData.description
          }
          
          const existingHomeworks = JSON.parse(localStorage.getItem('homeworkList') || '[]')
          existingHomeworks.unshift(newHomework)
          localStorage.setItem('homeworkList', JSON.stringify(existingHomeworks))
          
          // 设置刷新标记，让作业列表页面知道需要刷新数据
          localStorage.setItem('homeworkListNeedsRefresh', 'true')
          
          // 跳转回作业列表页面
          window.location.href = '#/assign-homework'
        } else {
          // 🔥 code !== 0，表示创建失败
          logger.error('❌ [HomeworkCreate] 作业创建失败，业务状态码异常');
          logger.error('❌ [HomeworkCreate] code:', response?.code);
          logger.error('❌ [HomeworkCreate] message:', response?.message);
          
          const errorMsg = response?.message || '创建作业失败，请检查输入信息';
          alert('❌ ' + errorMsg);
          
          // 不要跳转，让用户修改后重试
          return;
        }
        
      } catch (error) {
        logger.error('❌ [HomeworkCreate] 创建作业失败:', error)
        
        // 🔥 根据后端返回的实际错误信息显示
        let errorMessage = '创建作业失败，请稍后重试'
        
        // 尝试从各种可能的位置获取后端错误信息
        if (error.response?.data?.message) {
          errorMessage = error.response.data.message
        } else if (error.data?.message) {
          errorMessage = error.data.message
        } else if (error.message) {
          errorMessage = error.message
        }
        
        logger.error('❌ [HomeworkCreate] 显示错误消息:', errorMessage)
        alert('❌ ' + errorMessage)
        
        // 降级到本地存储
        logger.log('📦 [HomeworkCreate] 降级到本地存储')
        const newHomework = {
          id: Date.now(),
          title: homeworkForm.title || '未命名作业',
          startTime: homeworkForm.startTime || new Date().toISOString(),
          endTime: homeworkForm.endTime || new Date().toISOString(),
          questionCount: selectedQuestions.value.length,
          registrationCount: 0,
          status: '未发布',
          creator: '当前用户',
          questions: selectedQuestions.value,
          teams: selectedTeams.value,
          description: homeworkForm.description
        }
        
        const existingHomeworks = JSON.parse(localStorage.getItem('homeworkList') || '[]')
        existingHomeworks.unshift(newHomework)
        localStorage.setItem('homeworkList', JSON.stringify(existingHomeworks))
      }
    }



    // 监听选项卡变化
    watch(activeTab, (newTab) => {
      logger.log('🔄 [HomeworkCreate] 选项卡切换到:', newTab)
      if (newTab === 'homework') {
        // 当切换到"我的试题"选项卡时，调用API获取题目
        loadMyQuestions()
      } else if (newTab === 'public') {
        // 当切换到"公开题库"选项卡时，调用API获取公开题目
        loadPublicQuestions()
      }
    })

    // 生命周期
    onMounted(() => {
      // 页面加载时默认加载"我的试题"
      loadMyQuestions()
      
      // 🔥 自动加载我的班级
      logger.log('🏫 [HomeworkCreate] 页面加载，自动加载班级信息...')
      loadMyTeams()
    })

    return {
      activeTab,
      availableQuestions,
      selectedQuestions,
      selectedTeams,
      homeworkForm,
      teams,
      isLoadingTeams,
      myQuestionsPagination,
      publicQuestionsPagination,
      myJumpPage,
      publicJumpPage,
      mySearchKeyword,
      mySearchDifficulty,
      publicSearchKeyword,
      publicSearchDifficulty,
      addQuestionToHomework,
      removeQuestionFromHomework,
      toggleTeam,
      loadMyTeams,
      createNewHomework,
      changeMyQuestionsPage,
      changePublicQuestionsPage,
      jumpToMyQuestionsPage,
      jumpToPublicQuestionsPage,
      searchMyQuestions,
      resetMySearch,
      searchPublicQuestions,
      resetPublicSearch
    }
  }
}
</script>

<style scoped>
.homework-create-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 20px;
}

/* 页面头部样式 */
.page-header {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-title-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title-icon {
  font-size: 24px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0;
  font-weight: 600;
}

/* 主要内容区域 */
.main-content {
  max-width: 1400px;
  margin: 0 auto;
}

.container {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 表单样式 */
.form-section {
  margin-bottom: 30px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  align-items: end;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}

.form-group.large {
  flex: 2;
}

.form-group.full-width {
  flex: 1;
  width: 100%;
}

.form-group label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-input,
.form-select,
.form-textarea {
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: #4CAF50;
}

.form-textarea {
  resize: vertical;
  min-height: 120px;
}

/* 编辑器工具栏 */
.editor-toolbar {
  display: flex;
  gap: 5px;
  padding: 8px;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px 4px 0 0;
  margin-bottom: -1px;
}

.toolbar-btn {
  padding: 4px 8px;
  border: 1px solid #ccc;
  background: white;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

.toolbar-btn:hover {
  background: #f0f0f0;
}

/* 题目选择区域 */
.questions-section {
  margin-bottom: 30px;
}

/* 搜索过滤栏 */
.search-filter-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  align-items: center;
}

.search-filter-bar .search-input {
  flex: 1;
  padding: 10px 15px;
  border: 2px solid #e1e8ed;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.search-filter-bar .search-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.search-filter-bar .difficulty-select {
  padding: 10px 15px;
  border: 2px solid #e1e8ed;
  border-radius: 6px;
  font-size: 14px;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 150px;
}

.search-filter-bar .difficulty-select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.search-filter-bar .search-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.search-filter-bar .search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.5);
}

.search-filter-bar .reset-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #6c757d, #5a6268);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 2px 8px rgba(108, 117, 125, 0.3);
}

.search-filter-bar .reset-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(108, 117, 125, 0.5);
}

.section-tabs {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  background: #ff9800;
  padding: 10px 15px;
  border-radius: 6px;
}

.tab-btn {
  background: #ff9800;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.tab-btn.active {
  background: #e68900;
}

.tab-btn:hover {
  background: #e68900;
}

.tab-info {
  margin-left: auto;
  color: white;
  font-size: 14px;
}

.count {
  font-weight: bold;
  color: #fff;
}

/* 题目表格 */
.questions-table-container,
.homework-questions-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.questions-table {
  width: 100%;
  border-collapse: collapse;
}

.questions-table th {
  background: #4CAF50;
  color: white;
  padding: 12px 15px;
  text-align: left;
  font-weight: 500;
  font-size: 14px;
}

.questions-table td {
  padding: 12px 15px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
  color: #333;
}

.table-row:hover {
  background: #f9f9f9;
}

.title-cell {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.action-cell {
  text-align: center;
}

.add-btn {
  background: #4CAF50;
  color: white;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-btn:hover {
  background: #45a049;
}

.remove-btn {
  background: #f44336;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.remove-btn:hover {
  background: #da190b;
}

/* 分数输入框样式 */
.score-cell {
  padding: 8px;
}

.score-input {
  width: 80px;
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
  transition: all 0.2s;
}

.score-input:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.score-input:hover {
  border-color: #999;
}

.empty-row {
  text-align: center;
  color: #999;
  padding: 40px 20px;
  font-style: italic;
}

.tip {
  font-size: 12px;
  color: #666;
}

.highlight {
  color: #ff9800;
  font-weight: bold;
}

/* 本次作业题目 */
.homework-questions-section {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 10px;
  background: #4CAF50;
  color: white;
  padding: 12px 20px;
  border-radius: 6px;
  margin-bottom: 15px;
}

.section-number {
  background: white;
  color: #4CAF50;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
}

.questions-count {
  margin-left: auto;
  font-size: 14px;
}

/* 团队选择 */
.team-section {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.team-section .section-title {
  font-size: 18px;
  color: #333;
  margin: 0;
}

.refresh-teams-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  display: flex;
  align-items: center;
  gap: 5px;
}

.refresh-teams-btn .icon {
  font-size: 14px;
}

.refresh-teams-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.5);
}

.refresh-teams-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 加载中状态 */
.loading-teams {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 15px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-teams p {
  margin: 0;
  font-size: 14px;
}

/* 班级卡片网格 */
.team-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.team-card {
  border: 2px solid #ddd;
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.team-card:hover {
  border-color: #667eea;
  transform: translateY(-3px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

.team-card.selected {
  border-color: #4CAF50;
  background: linear-gradient(135deg, #e8f5e9, #c8e6c9);
  box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
}

.team-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.team-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.team-id {
  font-size: 12px;
  color: #7f8c8d;
  margin-bottom: 8px;
}

.team-member-count {
  font-size: 13px;
  color: #667eea;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.team-member-count .icon {
  font-size: 14px;
}

/* 无班级提示 */
.no-teams {
  text-align: center;
  padding: 60px 20px;
  color: #7f8c8d;
  background: #f8f9fa;
  border-radius: 12px;
  border: 2px dashed #dee2e6;
}

.no-teams .icon {
  font-size: 60px;
  margin-bottom: 15px;
  display: block;
}

.no-teams p {
  font-size: 16px;
  margin: 0 0 8px 0;
  color: #495057;
}

.no-teams small {
  font-size: 13px;
  color: #adb5bd;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 30px;
}

.create-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.2s;
  background: #2196F3;
  color: white;
}

.create-btn:hover {
  background: #1976D2;
}

/* 分页样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
  padding: 15px;
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid #4CAF50;
  background: white;
  color: #4CAF50;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.page-btn:hover:not(:disabled) {
  background: #4CAF50;
  color: white;
}

.page-btn:disabled {
  border-color: #ccc;
  color: #ccc;
  cursor: not-allowed;
  opacity: 0.5;
}

.page-info {
  font-size: 14px;
  color: #666;
  padding: 0 10px;
}

/* 页码跳转样式 */
.page-jump {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-input {
  width: 70px;
  padding: 8px 10px;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  text-align: center;
  transition: all 0.3s ease;
}

.page-input:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.1);
}

.jump-btn {
  padding: 8px 16px;
  background: white;
  border: 2px solid #4CAF50;
  color: #4CAF50;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.jump-btn:hover {
  background: #4CAF50;
  color: white;
  transform: translateY(-2px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .homework-create-page {
    padding: 10px;
  }
  
  .container {
    padding: 20px;
  }
  
  .form-row {
    flex-direction: column;
    gap: 15px;
  }
  
  .section-tabs {
    flex-wrap: wrap;
  }
  
  .team-grid {
    justify-content: center;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
}
</style> 